var express = require('express');
var router = express.Router();
const fs = require("fs");
const banner = require("../sql/banner")
const sql = require("../sql/sql")
const uuid = require("uuid")

/* GET users listing. */
router.get('/', function(req, res, next) {
  // 读取banner文件数据
  sql.getData(banner).then(data=>{
    res.render("banner",{
      index:1,
      data
    });
  })
});

router.post('/addAction', function (req, res, next) {
  req.files.forEach(val => {
      let oldName = val.path;
      let newName = oldName + "-" + val.originalname;
      fs.renameSync(oldName, newName);
      newName = newName.replace(/\\/g, "/");
      newName = newName.replace("public/", "");
      let imgPath = "http://localhost:4000" + "/" + newName;

      // 图片存入数据库
      sql.addData(banner, {
          bannerId: "banner-" + uuid.v1(),
          name: req.body.imgName,
          describe: req.body.imgDesc,
          src: imgPath,
          time: Date.now()
      }).then(() => {
          res.redirect("/banner");
      })
  });

})

router.get('/del', function(req, res, next) {
  sql.delData(banner,{bannerId:req.query.id}).then(()=>{
    res.redirect("/banner")
  })
});

module.exports = router;
